<?php
class Model_mediaset extends Model {

	var $_tbl_name;
	var $_tbl_pri;
	var $_ispublish;
	function Model_mediaset() {
		// Call the Model constructor
		parent::Model();
		$this->_tbl_name = "tbl_media_set";
		$this->_tbl_pri = "id";
		$this->_ispublish = "1";
	}

	/**
	 *
	 *
	 */
	function find($id) {
		$this->db->where("id", $id);
		$query = $this->db->get($this->_tbl_name);

		if ($query->num_rows() > 0) {
			return $query->first_row('array');
		}
		return null;
	}

	/**
	 *
	 *
	 */
	function find_by_ids($ids) {
		$this->db->where_in("id", $ids);
		$query = $this->db->get($this->_tbl_name);
		if ($query->num_rows() > 0) {
			return $query->result_array();
		}
		return null;
	}
	/**
	 *
	 *
	 */
	function browse($keyword, $fromdate, $todate, $limit = 10, $offset = 0, $order_by = 'sort', $method = "ASC"){
		$this->db->from($this->_tbl_name);
		if(!empty($keyword)){
			$this->db->like($this->_tbl_name.'.title', $keyword);
			$this->db->or_like($this->_tbl_name.'.content', $keyword);
		}
		if(!empty($fromdate) AND !empty($todate)){
			$this->db->where(array('created_date <' => $todate, 'created_date >' => $fromdate));
		}
		elseif(!empty($fromdate)){
			$this->db->where('created_date >' , $fromdate);
		}
		elseif(!empty($todate)){
			$this->db->where('created_date <' , $todate);
		}
		$this->db->where('publish' , $this->_ispublish);
		$this->db->order_by($order_by, $method);
		$this->db->limit($limit, $offset);

		$query = $this->db->get();
	//	echo $this->db->last_query();
		if ($query->num_rows() > 0) {
			return $query->result_array();
		}
		return null;
	}
	/**
	 *
	 *
	 */
	function fetch_all()
	{
		$this->db->order_by("sort");
		$query = $this->db->get($this->_tbl_name);

		if ($query->num_rows() > 0) {
			return $query->result_array();
		}
		return null;
	}

	/**
	 *
	 *
	 */
	function insert_mediaset($data)
	{
		$sort = $this->get_max_sort();
		$data['sort'] = $sort + 1;
		$data['created_date'] = date("Y-m-d h:m:s");
		$data['modified_date'] = date("Y-m-d h:m:s");
		$this->db->insert($this->_tbl_name, $data);
		$id = $this->db->insert_id();
		return $id;
	}

	/**
	 *
	 *
	 */
	function update_mediaset($id, $data)
	{
		if(intval($id)){
			$data['modified_date'] = date("Y-m-d h:m:s");
			$this->db->where('id', $id);
			return $this->db->update($this->_tbl_name, $data);
		}
	}

	/**
	 *
	 *
	 */
	function delete_mediaset($id){
		// not detete item in group
		$this->db->where('id', $id);
		return $this->db->delete($this->_tbl_name);
	}

	/**
	 *
	 *
	 */
	function get_max_sort()
	{
		$this->db->select_max('sort');
		$query = $this->db->get($this->_tbl_name);
		if ($query->num_rows() > 0) {
			$first_row = $query->first_row('array');
			return $first_row['sort'];
		}
		return 0;
	}
}
?>